<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'

const props = defineProps<{
  modelValue: string
  label?: string
  placeholder?: string
  rules?: any
}>()
const emit = defineEmits(['update:modelValue'])

const showPwd = ref('password')
const iconVisible = ref(false)
let iconTimer: ReturnType<typeof setTimeout> | null = null
let pwdTimer: ReturnType<typeof setTimeout> | null = null

const handleFocus = () => {
  iconVisible.value = true
  if (iconTimer) clearTimeout(iconTimer)
}
const handleBlur = () => {
  iconTimer = setTimeout(() => {
    iconVisible.value = false
    iconTimer = null
  }, 3000)
}
watch(showPwd, (val) => {
  if (pwdTimer) clearTimeout(pwdTimer)
  if (val === 'text') {
    pwdTimer = setTimeout(() => {
      showPwd.value = 'password'
      pwdTimer = null
    }, 2000)
  }
})
onBeforeUnmount(() => {
  if (iconTimer) clearTimeout(iconTimer)
  if (pwdTimer) clearTimeout(pwdTimer)
})

const updateValue = (val: string) => emit('update:modelValue', val)
</script>

<template>
  <cVanfield
    :label="label || '密码'"
    :placeholder="placeholder || '请输入密码'"
    label-width="15vmin"
    :rules="rules"
    :type="showPwd"
    clearable
    @blur="handleBlur"
    @focus="handleFocus"
    :model-value="modelValue"
    @update:model-value="updateValue"
  >
    <template #right-icon>
      <div class="flex" v-show="iconVisible">
        <van-icon name="closed-eye" @click="showPwd = 'text'" v-show="showPwd === 'password'" />
        <van-icon name="eye-o" @click="showPwd = 'password'" v-show="showPwd === 'text'" />
      </div>
    </template>
  </cVanfield>
</template>

<style lang="scss" scoped> 
.van-hairline--top-bottom:after {
    display: none;
}
</style>